<template>
  <el-drawer
    title="填写参数"
    size="40%"
    :visible.sync="visible"
    :before-close="onClose"
    :wrapper-closable="true"
    :destroy-on-close="true"
    append-to-body
    custom-class="alipay-config-drawer"
  >
    <div class="drawer-container">
      <el-form ref="infoFormModel" :model="saveObject" label-position="top" :rules="rules" v-loading="loading">
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="状态" prop="state">
            <el-radio-group v-model="saveObject.state">
              <el-radio :label="1">启用</el-radio>
              <el-radio :label="0">停用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="saveObject.remark" placeholder="请输入" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-divider>
      <el-tag type="danger">
        {{ saveObject.ifCode }} 服务商参数配置
      </el-tag>
    </el-divider>

    <el-form ref="isvParamFormModel" :model="ifParams" label-position="top" :rules="ifParamsRules" v-loading="loading">
      <el-row :gutter="16">
        <el-col :span="24">
          <el-form-item label="环境配置" prop="sandbox">
            <el-radio-group v-model="ifParams.sandbox">
              <el-radio :label="1">沙箱环境</el-radio>
              <el-radio :label="0">生产环境</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="应用AppID" prop="appId">
            <el-input v-model="ifParams.appId" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="应用私钥" prop="privateKey">
            <el-input v-model="ifParams.privateKey" :placeholder="ifParams.privateKey_ph" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="支付宝公钥" prop="alipayPublicKey">
            <el-input v-model="ifParams.alipayPublicKey" :placeholder="ifParams.alipayPublicKey_ph" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="接口签名方式(推荐使用RSA2)" prop="signType">
            <el-radio-group v-model="ifParams.signType" default="RSA">
              <el-radio label="RSA">RSA</el-radio>
              <el-radio label="RSA2">RSA2</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="公钥证书" prop="useCert">
            <el-radio-group v-model="ifParams.useCert" default="1">
              <el-radio :label="1">使用证书（请使用RSA2私钥）</el-radio>
              <el-radio :label="0">不使用证书</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="应用公钥证书（.crt格式）" prop="appPublicCert">
            <el-input v-model="ifParams.appPublicCert" disabled />
            <FileUpload
              :fileUrl="ifParams.appPublicCert"
              @success="(response) => uploadSuccess(response, 'appPublicCert')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="支付宝公钥证书（.crt格式）" prop="alipayPublicCert">
            <el-input v-model="ifParams.alipayPublicCert" disabled />
            <FileUpload
              :fileUrl="ifParams.alipayPublicCert"
              @success="(response) => uploadSuccess(response, 'alipayPublicCert')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="支付宝根证书（.crt格式）" prop="alipayRootCert">
            <el-input v-model="ifParams.alipayRootCert" disabled />
            <FileUpload
              :fileUrl="ifParams.alipayRootCert"
              @success="(response) => uploadSuccess(response, 'alipayRootCert')"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div style="position: absolute; bottom: 0; width: 100%; border-top: 1px solid #e8e8e8; padding: 10px 16px; text-align: right; left: 0; background: #fff; border-radius: 0 0 2px 2px;">
      <el-button style="margin-right: 8px" @click="onClose">取消</el-button>
      <el-button type="primary" @click="onSubmit">确定</el-button>
    </div>
  </div>
  </el-drawer>
</template>

<script>
import { savePayConfig, req, getIsvPayConfigUnique, upload } from '@/api/pay/isv/IsvPayIfConfigList'
import FileUpload from '@/components/FileUpload'

export default {
  components: {
    FileUpload
  },
  props: {
    callbackFunc: { type: Function, default: () => ({}) }
  },

  data () {
    return {
      btnLoading: false,
      visible: false, // 抽屉开关
      isAdd: true,
      action: upload.cert, // 上传文件地址
      saveObject: {}, // 保存的对象
      ifParams: {}, // 参数配置对象
      rules: {
        ifRate: [{ required: false, pattern: /^(([1-9]{1}\d{0,1})|(0{1}))(\.\d{1,4})?$/, message: '请输入0-100之间的数字，最多四位小数', trigger: 'blur' }]
      },
      ifParamsRules: {
        pid: [{ required: true, message: '请输入合作伙伴身份（PID）', trigger: 'blur' }],
        appId: [{ required: true, message: '请输入应用AppID', trigger: 'blur' }],
        privateKey: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.isAdd && !value) {
              callback(new Error('请输入应用私钥'))
            }
            callback()
        } }],
        alipayPublicKey: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.useCert === 0 && this.isAdd && !value) {
              callback(new Error('请输入支付宝公钥'))
            }
            callback()
        } }],
        appPublicCert: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.useCert === 1 && !this.ifParams.appPublicCert) {
              callback(new Error('请上传应用公钥证书（.crt格式）'))
            }
            callback()
        } }],
        alipayPublicCert: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.useCert === 1 && !this.ifParams.alipayPublicCert) {
              callback(new Error('请上传支付宝公钥证书（.crt格式）'))
            }
            callback()
        } }],
        alipayRootCert: [{ trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.ifParams.useCert === 1 && !this.ifParams.alipayRootCert) {
              callback(new Error('请上传支付宝根证书（.crt格式）'))
            }
            callback()
        } }]
      },
      loading: false
    }
  },
  methods: {
    // 弹层打开事件
    show: function (isvNo, record) {
      if (this.$refs.infoFormModel !== undefined) {
        this.$refs.infoFormModel.resetFields()
      }
      if (this.$refs.isvParamFormModel !== undefined) {
        this.$refs.isvParamFormModel.resetFields()
      }

      // 数据初始化
      this.saveObject = {
        infoId: isvNo,
        ifCode: record.ifCode,
        state: record.ifConfigState === 0 ? 0 : 1
      }

      // 参数配置对象，数据初始化
      this.ifParams = {
        sandbox: 0,
        signType: 'RSA2',
        useCert: 0,
        privateKey: '',
        privateKey_ph: '请输入',
        alipayPublicKey: '',
        alipayPublicKey_ph: '请输入'
      }
      this.visible = true
      this.$nextTick(() => {
        this.getIsvPayConfig()
      })
    },
    // 支付参数配置
    getIsvPayConfig () {
      const that = this
      that.loading = true
      // 获取支付参数
      getIsvPayConfigUnique(that.saveObject.infoId, that.saveObject.ifCode)
        .then(res => {
          if (res && res.data && res.data.ifParams) {
            that.saveObject = res.data
              that.ifParams = JSON.parse(res.data.ifParams)
              that.ifParams.privateKey_ph = that.ifParams.privateKey || '请输入'
              that.ifParams.privateKey = ''
              that.ifParams.alipayPublicKey_ph = that.ifParams.alipayPublicKey || '请输入'
              that.ifParams.alipayPublicKey = ''
              that.isAdd = false
          } else {
            that.isAdd = true
          }
        })
        .catch(error => {
          console.error('获取支付配置失败:', error)
          that.$message.error('获取支付配置失败')
          that.isAdd = true
        })
        .finally(() => {
          that.loading = false
        })
    },
    // 表单提交
    onSubmit () {
      const that = this
      this.$refs.infoFormModel.validate(valid => {
        this.$refs.isvParamFormModel.validate(valid2 => {
          if (valid && valid2) { // 验证通过
            that.btnLoading = true
            const reqParams = {}
            reqParams.infoId = that.saveObject.infoId
            reqParams.ifCode = that.saveObject.ifCode
            reqParams.ifRate = that.saveObject.ifRate
            reqParams.state = that.saveObject.state
            reqParams.remark = that.saveObject.remark
            // 支付参数配置不能为空
            if (Object.keys(that.ifParams).length === 0) {
              this.$message.error('参数不能为空！')
              return
            }
            // 脱敏数据为空时，删除该key
            that.clearEmptyKey('privateKey')
            that.clearEmptyKey('alipayPublicKey')
            reqParams.ifParams = JSON.stringify(that.ifParams)
            // 请求接口
            if (Object.keys(reqParams).length === 0) {
              this.$message.error('参数不能为空！')
              return
            }
            savePayConfig (reqParams.infoId, reqParams.ifCode, reqParams).then(res => {
              that.$message.success('保存成功')
              that.visible = false
              that.btnLoading = false
              that.callbackFunc()
            })
          }
        })
      })
    },
    // 脱敏数据为空时，删除对应key
    clearEmptyKey (key) {
      if (!this.ifParams[key]) {
        this.ifParams[key] = undefined
      }
      this.ifParams[key + '_ph'] = undefined
    },
    // 上传文件成功回调方法，参数value为文件地址，name是自定义参数
    uploadSuccess(response, name) {
      let ossId = '';
      if (response) {
        if (response.data && response.data.ossId) {
          ossId = response.data.ossId;
        } else if (response.ossId) {
          ossId = response.ossId;
        }
      }
      this.ifParams[name] = ossId;
      this.$forceUpdate();
    },
    onClose () {
      this.visible = false
    }
  }
}
</script>
<style lang="less" scoped>
.alipay-config-drawer {
  .drawer-container {
    padding: 20px;
  }
}

.el-divider {
  margin: 24px 0;
}
</style>
